/**
 * Created by ����Ӱ�� on 2018/9/4.
 */

function ismobile() {
    //判断访问终端
    var browser = {
        versions: function () {
            var u = navigator.userAgent, app = navigator.appVersion;
            return {
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
                iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
                weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
                qq: u.match(/\sQQ/i) == " qq" //是否QQ
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    };

    if (browser.versions.mobile == true) {
        if (browser.versions.iPhone == true) {
            return '1';
        } else if (browser.versions.android == true) {
            return '0';
        }
    } else {

    }
}

var Date1;

//detailAjax(28,"600002880522","6429F89D-53C5-A2CF-CF46-49B491F8CD90",100,20)

var isMobile = ismobile();

if (isMobile == 0) {

    window.android.getAndroidId(JSON.stringify("oo"));
}

function WebViewDidFinishLoad() {

    var message = {

        "VcWay": "SendId"
    };

    window.webkit.messageHandlers.CallOrderDetailsModel.postMessage(message);
}
function receive_android_projectid(k) {//接受安卓参数

    var obj = $.parseJSON(k);

    detailAjax(obj.uid, obj.order_code, obj.TOKEN, obj.port, obj.orderstatus, obj.addressID);

    Date1 = obj.date

}
function receiveiOSVcData(i) {//接受ios参数

    var obj = $.parseJSON(i);

    detailAjax(obj.uid, obj.order_code, obj.TOKEN, obj.port, obj.orderStatus, obj.addressID);

    Date1 = obj.date;

}

function detailAjax(uid, code, token, port, orderStatus, addressID) {

    //console.log(orderStatus)

    $.ajax({

        type: "POST",

        url: url + "users/orderinfo",

        dataType: "json",

        //anysc: false,

        data: {"uid": uid, "order_code": code},

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);
        },
        success: function (data) {

            //console.log(data);

            if (data.data.codes == 200) {

                var result = data.data.data;

                if (result.belong_model == 600) {

                    var html;

                    if (orderStatus == 0) {//待支付

                        if (!result.meal_info) {

                            result.meal_info = {};
                        }
                        html = template("personOrderDetailsTpl2", data)

                    } else if (orderStatus == 70 || orderStatus == 71 || orderStatus == 72) {//取消状态

                        if (!result.meal_info) {

                            result.meal_info = {};
                        }

                        html = template("personOrderDetailsTpl3", data)

                    } else {//正常状态

                        if (!result.meal_info) {

                            result.meal_info = {};

                        }

                        html = template("personOrderDetailsTpl", data)
                    }
                }

                $("#order_body").html(html);

                if (isiphoneX) {

                    $(".order_follow").css("padding-bottom", "0.484rem").prev().css("margin-bottom", "2.184rem");

                }

                if (result.created_at == 0) {

                    $(".order_time .buyTime span").html("无");//下单时间

                } else {

                    $(".order_time .buyTime span").html(timeFormatDate((result.created_at) * 1000));//下单时间

                }
                if (result.pay_at == 0) {

                    $(".order_time .payTime span").html("无");//付款时间

                } else {

                    $(".order_time .payTime span").html(timeFormatDate((result.pay_at) * 1000));//付款时间

                }

                if (result.take_at == 0) {

                    $(".order_time .takeTime span").html("无");//取货时间

                } else {

                    $(".order_time .takeTime span").html(timeFormatDate((result.take_at) * 1000));//取货时间

                }

                if (result.finish_at == 0) {

                    $(".order_time .returnTime span").html("无");//归还时间

                } else {

                    $(".order_time .returnTime span").html(timeFormatDate((result.finish_at) * 1000))//归还时间

                }

                $(".order_Time span").html(timeFormat(result.start_time) + "~" + timeFormat(result.old_end_time));//订单时间

                $(".date span").html(Date1.slice(0, 10) + " ~ " + Date1.slice(17, 27));//日期

                if (result.order_type == 200) {//延时订单

                    $(".server_price span").html(result.pay_fee);//租金

                    $(".service_charge").style.display = "none";

                } else {//普通订单

                    $(".server_price span").html((Number(result.pay_fee) - Number(result.security_deposit) + Number(result.use_coupon_count) - Number(result.shipping_fee) || 0).toFixed(2));//租金

                }

                if (result.postpone_status == 201 || result.postpone_status == 300) {//延期时间及金额

                    var detailTime = "<p class='detailtime'>延期时间：<span>" + timeFormat(result.old_end_time) + "~" + timeFormat(result.end_time) + "</span></p><p class='detailmoney'>延期金额：￥<span>" + result.postpone_total_count + "</span></p>";

                    $(".order_time").append(detailTime)

                }

            } else {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({
                        "VcData": data.data.msg,
                        "VcWay": "ShowMessage"
                    });

                } else if (isMobile == 0) {

                    window.android.toastMsg(data.data.msg);
                }

            }
            //invite(data.data.data.by_uid);

            $(".address_phone1").on("click", function () {//点击拨打电话 只传电话
                var phone = data.data.data.by_mobile;

                if (isMobile == 1) {

                    var message = {

                        "VcData": phone,

                        "VcWay": "TelePhone"
                    };

                    window.webkit.messageHandlers.CallOrderDetailsModel.postMessage(message);

                } else if (isMobile == 0) {

                    window.android.jumpToCallPhone(phone);
                }
            });

            $(".chat").on("click", function () {//点击聊天  数据来自订单跟踪接口

                ordertail(uid, code, token, port)

            });


            $(".order_goodsMsg").on("click", function () {//点击每条详情跳转到详情页面


                var json = {"goods_id": data.data.data.goods_id, "addressID": addressID};

                if (json.goods_id && json.addressID) {


                    if (isMobile == 1) {

                        var message = {

                            "VcData": json,

                            "VcName": "ManPowerDetails",

                            "VcWay": "PushVCName"
                        };

                        window.webkit.messageHandlers.CallOrderDetailsModel.postMessage(message);

                    } else if (isMobile == 0) {

                        window.android.jumpToProjectFieldDetail(JSON.stringify(json));
                    }
                }


            });

            $(".p").on("click", function () {//点击订单跟踪

                var json = {"ordertype": data.data.data.belong_model, "order_code": data.data.data.order_code};

                if (json.order_code && json.ordertype) {

                    if (isMobile == 1) {

                        var message = {

                            "VcData": json,

                            "VcName": "OrderStatus",

                            "VcWay": "PushVCName"
                        };

                        window.webkit.messageHandlers.CallOrderDetailsModel.postMessage(message);

                    } else if (isMobile == 0) {

                        window.android.jumpToFollowOrder(JSON.stringify(json));
                    }
                }


            });


            $(".copyAddr").on("click", function () {

                var html = $(".addrC b").html();

                if (html.length > 0) {

                    if (isMobile == 1) {

                        window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({
                            "VcData": html,
                            "VcWay": "CopyAddress"
                        });

                        window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({
                            "VcData": "复制成功",
                            "VcWay": "ShowMessage"
                        });

                    } else if (isMobile == 0) {

                        window.android.addClipboard(html);

                        window.android.toastMsg("复制成功");
                    }
                } else {
                    if (isMobile == 1) {

                        window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({
                            "VcData": "复制失败",
                            "VcWay": "ShowMessage"
                        });

                    } else if (isMobile == 0) {

                        window.android.toastMsg("复制失败");
                    }
                }


            })
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({
                    "VcData": "联网失败",
                    "VcWay": "ShowMessage"
                });

            } else if (isMobile == 0) {

                window.android.toastMsg("联网失败");
            }
        }
    });
}
//订单跟踪接口（点击聊天调用）
function ordertail(uid, code, token, port) {

    $.ajax({

        type: "POST",

        url: url + "users/ordertail",

        dataType: "json",

        //anysc: false,

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);
        },
        data: {
            "uid": uid,

            "order_code": code,

            "port": port
        },
        success: function (data) {

            // console.log(data)

            if (data.data == null) {

                return false;

            } else if (data.data.codes == "200") {

                if (isMobile == 1) {

                    var message = {

                        "VcData": {

                            'mobile': data.data.data.showUserInfo.side_mobile,

                            'name': data.data.data.showUserInfo.name,

                            'avatar': data.data.data.showUserInfo.avatar

                        },

                        "VcName": "Chat",

                        "VcWay": "PushVCName"
                    };

                    window.webkit.messageHandlers.CallOrderDetailsModel.postMessage(message);


                } else if (isMobile == 0) {

                    var json = {

                        'phone': data.data.data.showUserInfo.side_mobile,

                        'nickname': data.data.data.showUserInfo.name,

                        'avater': data.data.data.showUserInfo.avatar
                    };
                    window.android.jumpToIM(JSON.stringify(json));
                }

            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({
                    "VcData": "联网失败",
                    "VcWay": "ShowMessage"
                });

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");
            }
        }
    })
}
//格式化时间
function timeFormatDate(timeStamp) {

    var tmpTime = Date.parse(new Date(timeStamp));

    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }

    var newDate = new Date();
    newDate.setTime(tmpTime);
    return newDate.format('yyyy-MM-dd hh:mm');
}
//格式化时间
function timeFormat(time) {//201712271200
    var y = time.substring(0, 4);
    var m = time.substring(4, 6);
    var d = time.substring(6, 8);
    var h = time.substring(8, 10);
    var s = time.substring(10, 12);
    return (y + "-" + m + "-" + d + " " + h + ":" + s)
}
